<template>
  <div class="summary-content">
    <PartitionTitle type="line" fontSize="1rem">
      <span>年度累计</span>
      <span class="title-sub"> 生产效率 & 产线故障率 </span>
      <span class="title-sub-desc">截止至{{ queryParams.endMonth }}</span>
    </PartitionTitle>
    <div class="content">
      <div class="left" v-loading="chartLoading">
        <Chart
          v-if="option.xAxis.data.length > 0"
          ref="Chart"
          :option="option"
          @active-xAxis-change="handleActivexAxisChange"
        ></Chart>
        <div v-else class="no-data">暂无数据</div>
      </div>

      <div class="right" v-loading="tableLoading">
        <!-- <div class="top">
          <el-checkbox-group
            v-model="tableQueryparams"
            @change="getTableData()"
          >
            <el-checkbox label="produceEfficiency">生产效率不达标</el-checkbox>
            <el-checkbox label="stoppageRatio">产线故障率不达标</el-checkbox>
          </el-checkbox-group>
        </div> -->
        <TableForm
          ref="TableForm"
          :srouceTableData="srouceTableData"
          :columns="columns"
          :customFilter="false"
          :showIntersectionTip="false"
        ></TableForm>
      </div>
    </div>
  </div>
</template>
<script>
import Chart from "../../components/chart";
import TableForm from "@/components/TableForm";
import { getOption, colors } from "../chartOption";
import { columns } from "./table";
import {
  getSumLineYearProduce,
  getSumLineYearProduceDetail,
} from "@/api/reportFormAnalysis/failureRate";
export default {
  components: { Chart, TableForm },
  props: {
    queryParams: {
      type: Object,
      default: null,
    },
    // 横坐标默认选中值
    defaultxAxisActive: {
      type: String,
      default: null,
    },
  },
  data() {
    return {
      // 图表配置
      option: getOption(),
      // activeLine: null,
      // 表格源数据
      srouceTableData: [],
      // 表格列配置
      columns: [],
      // 表格的筛选条件
      tableQueryparams: [],
      chartLoading: false,
      tableLoading: false,
    };
  },
  methods: {
    async getChartData() {
      this.chartLoading = true;

      try {
        const params = {
          ...this.queryParams,
        };
        const res = await getSumLineYearProduce(params);
        const dataArr = res.data || [];

        let xAxisData = [];
        let seriesData1 = [];
        let seriesData2 = [];
        let standardAbnormalRatio = 0;
        for (let i = 0; i < dataArr.length; i++) {
          const ele = dataArr[i];
          xAxisData.push({
            value: ele.lineName,
            lineName: ele.lineName,
            lineCode: ele.lineCode,
            factoryDeptName: ele.factoryDeptName,
          });
          seriesData1.push({
            value: ele.produceEfficiency,
            mechanEfficiencyCoef: ele.mechanEfficiencyCoef,
            lineName: ele.lineName,
            lineCode: ele.lineCode,
            factoryDeptName: ele.factoryDeptName,
            itemStyle: {
              color: ele.produceEfficiencyOk == "N" ? "red" : colors[0],
            },
            label: {
              color: ele.produceEfficiencyOk == "N" ? "red" : colors[0],
            },
          });
          seriesData2.push({
            value: ele.abnormalRatio,
            lineName: ele.lineName,
            lineCode: ele.lineCode,
            factoryDeptName: ele.factoryDeptName,
            itemStyle: {
              color: ele.stoppageRatioOk == "N" ? "red" : colors[1],
            },
            label: {
              color: ele.stoppageRatioOk == "N" ? "red" : colors[1],
            },
          });
          standardAbnormalRatio =
            ele.standardAbnormalRatio || standardAbnormalRatio;
        }

        // 赋值
        this.option.xAxis.data = xAxisData;
        this.option.series[0].data = seriesData1;
        this.option.series[1].data = seriesData2;
        this.option.series[2].data = xAxisData.map(() => standardAbnormalRatio);
        this.option.series[2].markPoint.data = [
          {
            name: "",
            yAxis: standardAbnormalRatio,
            xAxis: xAxisData[xAxisData.length - 1].value,
            value: `${standardAbnormalRatio}%`,
          },
        ];
      } catch (error) {
        this.option.xAxis.data = [];
        this.option.series[0].data = [];
        this.option.series[1].data = [];
        this.option.series[2].data = [];
        this.option.series[2].markPoint.data = [];
        console.error(error);
      }

      // 获取表格数据
      await this.getTableData();

      // 图表默认选中第一个（在表格数据获取之后设置，因为要更具图表的选中项做表格的数据筛选）
      // 优先选中配置的值：defaultxAxisActive
      this.$nextTick(() => {
        const xaxisdata = this.option.xAxis.data;
        if (xaxisdata?.length > 0) {
          // 判断默认选中产线
          let defaultSelectedIndex = 0;

          if (this.defaultxAxisActive) {
            const lineIndex = xaxisdata.findIndex(
              (ele) => ele.value == this.defaultxAxisActive
            );
            if (lineIndex != -1) {
              defaultSelectedIndex = lineIndex;
            }
          }

          // 记录当前选中的产线
          // this.activeLine = xaxisdata[defaultSelectedIndex].value;
          // this.$refs.Chart.handlexAxisLabelChange(
          //   this.activeLine,
          //   defaultSelectedIndex
          // );
          this.$refs.Chart.handlexAxisLabelChange(
             xaxisdata[defaultSelectedIndex].value,
            defaultSelectedIndex
          );
        }
        // 关闭loading
        this.chartLoading = false;
      });
    },
    async getTableData() {
      this.tableLoading = true;

      try {
        const tableQueryparams = this.tableQueryparams;
        const params = {
          ...this.queryParams,
          produceEfficiencyOk: tableQueryparams.includes("produceEfficiency")
            ? "N"
            : "Y",
          stoppageRatioOk: tableQueryparams.includes("stoppageRatio")
            ? "N"
            : "Y",
        };
        const res = await getSumLineYearProduceDetail(params);

        const _columns = [...columns];
        _columns[0].conditionList = res.data?.factoryDeptNames || [];
        _columns[1].conditionList = res.data?.lineNames || [];

        const sumLineYearProduceVos = res.data?.sumLineYearProduceVos || [];

        let _srouceTableData = [];
        sumLineYearProduceVos.forEach((ele) => {
          if (ele.sumEquipStopVos?.length) {
            ele.sumEquipStopVos.forEach((row) => {
              _srouceTableData.push({
                ...row,
                equip_abnormalStopTimes: row.abnormalStopTimes, // 与汇总的字段冲突，加个前缀
                equip_abnormalStopMinutes: row.abnormalStopMinutes,
                ...ele,
              });
            });
          } else {
            _srouceTableData.push({
              ...ele,
              equipName: null,
              equip_abnormalStopTimes: null,
              equip_abnormalStopMinutes: null,
            });
          }
        });

        this.columns = _columns;
        this.srouceTableData = _srouceTableData;
      } catch (error) {
        this.srouceTableData = [];
        console.error(error);
      }

      // 列表过滤
      // this.$nextTick(() => {
      //   if (this.$refs.TableForm) {
      //     if (this.activeLine) {
      //       this.$refs.TableForm.updateFilterConditionValues({
      //         lineName: [this.activeLine],
      //       });
      //     }
      //   }
      // });

      this.tableLoading = false;
    },
    // 点击chart的横坐标（产线）
    handleActivexAxisChange(e, dataIndex) {
      // 记录当前选中的产线
      // this.activeLine = e?.length > 0 ? e[0].lineName : null;

      // 列表过滤
      this.$nextTick(() => {
        if (this.$refs.TableForm) {
          const selection = e.map((ele) => ele.lineName);
          if (selection.length > 0) {
            this.$refs.TableForm.updateFilterConditionValues({
              lineName: selection,
            });
          } else {
            this.$refs.TableForm.updateFilterConditionValues();
          }
        }
      });

      // 下钻到月度
      if (e?.length) {
        this.$emit("series-line-click", e[0], [
          this.option.series[0].data[dataIndex],
          this.option.series[1].data[dataIndex],
        ]);
      }
    },
  },
  watch: {
    queryParams: {
      handler(newVal) {
        if (!newVal) {
          return;
        }
        this.getChartData();
      },
      deep: true,
    },
  },
};
</script>
<style lang="scss" scoped>
.summary-content {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: flex-start;

  .content {
    width: 100%;
    flex: 1;
    position: relative;
    .left {
      width: 100%;
      height: 300px;
      border-radius: 4px;
      border: 1px solid #e9ebf1;
    }
    .right {
      width: 100%;
      margin-top: 20px;
      padding: 16px;
      border-radius: 4px;
      border: 1px solid #e9ebf1;
      display: flex;
      flex-direction: column;
      gap: 12px;
      background-color: #ffffff;
      .top {
        display: flex;
        justify-content: space-between;
        align-items: center;
        img {
          width: 24px;
          cursor: pointer;
        }
      }
      .custom-table-container {
        flex: 1;
        overflow: hidden;
      }
    }
  }
}

.no-data {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  font-size: 13px;
  color: #cccccc;
}
</style>
